package com.acheli.registry.item;

import com.acheli.ACHeli;
import com.acheli.registry.config.CustomDataBus;
import com.acheli.registry.config.GsonFactoryConfig;
import com.acheli.registry.entity.ACHEntities;
import com.acheli.registry.factories.ACHFactories;
import com.acheli.registry.network.ACHMessages;
import com.acheli.registry.network.packet.RideableSpawnS2CPacket;
import com.acheli.rideable.entites.RideableEntity;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.food.FoodProperties;
import net.minecraft.world.item.*;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.acheli.ACHeli.LOGGER;
import static com.acheli.ACHeli.MODID;

public class ACHItems {
    public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
//    public static final RegistryObject<Item> UH_1_D_BODY = ITEMS.register("uh_1d_body", () -> new BlockItem(ACHBlocks.UH_1_D_BODY.get(), new Item.Properties()));

    // Creates a new food item with the id "examplemod:example_id", nutrition 1 and saturation 2
    public static final RegistryObject<Item> EXAMPLE_ITEM = ITEMS.register("example_item", () -> new Item(new Item.Properties().food(new FoodProperties.Builder()
            .alwaysEat().nutrition(1).saturationMod(2f).build())));
    // 注册普通物品（右键生成实体）
    public static RegistryObject<Item> UH_1D_SAR_SPAWN_EGG = rideableSpawnerProvider(ACHItems.ITEMS, ACHFactories.UH_1D_SAR_FACTORY);

    public static List<RegistryObject<Item>> spawnEggs = new ArrayList<>();

    public static RegistryObject<Item> rideableSpawnerProvider(DeferredRegister<Item> ITE, String factoryName) {
        String tagName = factoryName+"_spawn_egg";
        LOGGER.info("Rideable SpawnEgg:  "+tagName+"  has been register.");
        return ITE.register(
                tagName,
                () -> new Item(new Item.Properties()) {
                    // 重写右键方法
                    @Override
                    public InteractionResult useOn(UseOnContext context) {
                        Level level = context.getLevel();
                        if (!level.isClientSide) { // 仅服务端执行
                            // 创建实体并设置位置
                            RideableEntity entity = new RideableEntity(ACHEntities.RIDEABLE_ENTITY_TYPE.get(), level);
                            entity.setUp(factoryName);
                            entity.setPos(context.getClickLocation()); // 设置生成位置为点击点
                            level.addFreshEntity(entity); // 将实体加入世界

                            RideableSpawnS2CPacket packet = new RideableSpawnS2CPacket(entity.getId(), factoryName);
                            ACHMessages.CHANNEL.send(
                                    PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> entity),
                                    packet
                            ); // 广播给所有追踪该RideableEntity的玩家

                        }
                        return InteractionResult.SUCCESS;
                    }
                }
        );
    }
    public static final DeferredRegister<CreativeModeTab> CREATIVE_MODE_TABS = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, MODID);
    public static final RegistryObject<CreativeModeTab> EXAMPLE_TAB = CREATIVE_MODE_TABS.register("vehicles", () -> CreativeModeTab.builder()
            .withTabsBefore(CreativeModeTabs.COMBAT)
            .title(Component.translatable("itemGroup.archers_helicopter.vehicles"))
            .icon(() -> UH_1D_SAR_SPAWN_EGG.get().getDefaultInstance())
            .displayItems((parameters, output) -> {
                output.accept(UH_1D_SAR_SPAWN_EGG.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event
                for (RegistryObject<Item> spawnEgg : spawnEggs.stream().toList()) {
                    output.accept(spawnEgg.get());
                }
            }).build());
    public static void addCreative(BuildCreativeModeTabContentsEvent event)
    {
        if (event.getTabKey() == CreativeModeTabs.SPAWN_EGGS) {
            event.accept(UH_1D_SAR_SPAWN_EGG);
        }

    }
    public static void register(IEventBus modEventBus) {
        for (String name : ACHeli.GsonEntitiesFactoryRegisterMap.keySet().stream().toList()) {
            spawnEggs.add(rideableSpawnerProvider(ACHItems.ITEMS, name));
        }
        ITEMS.register(modEventBus);
        CREATIVE_MODE_TABS.register(modEventBus);
    }
}
